
local assert     = assert
local require    = require
local bit        = bit
local coroutine  = coroutine
local debug      = debug
local io         = io
local pairs      = pairs
local ipairs     = ipairs
local math       = math
local os         = os
local print      = print
local pcall      = pcall
local xpcall     = xpcall
local rawget     = rawget
local rawset     = rawset
local select     = select
local string     = string
local table      = table
local tonumber   = tonumber
local tostring	 = tostring
local error      = error
local type       = type
local unpack     = unpack
local setmetatable = setmetatable
local getmetatable = getmetatable
local ngx = ngx

local string_char  = string.char
local string_sub   = string.sub
local string_byte  = string.byte
local string_gsub  = string.gsub
local string_find  = string.find
local string_upper = string.upper

local math_fmod   = math.fmod
local math_floor  = math.floor
local math_pow    = math.pow
local math_abs    = math.abs

local table_insert = table.insert

local os_date = os.date;
local table_concat = table.concat;


local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");
local ns_time    = require("modules.commhm.time");
local ns_network = require("modules.commhm.network");
local ns_utf8    = require("modules.commhm.utf8");

local ns_auth_comm_checker = require("modules.commhm.auth_comm_checker")

local CHtmlTable = require( "modules.html_page.CHtmlTable" )


local table_tostring = table.tostring
local table_loadstring = table.loadstring



local FOO = {
	_VERSION = '0.12.1',

	show_txt = {},

	now_ = 0,
};


FOO.ip_desc = {

	--[[

	["120.24.64.132"]   = "test_132",
	["211.159.183.137"] = "cn_xianqian",
	["47.75.147.207"]   = "hw_xianqian",

	-----------------ma----------------------------
	["111.230.129.81"]  = "center_config0",
	["139.199.5.123"]   = "ma_123_gate_o0",
	["134.175.65.176"]  = "gate_o1",
	["159.75.43.142"]   = "gate_o2",

	["123.207.121.196"]   = "ma_ssdb_6_dc16",
	["111.230.219.104 "]  = "ma_ssdb_7_dc27",

	-----------------map + profile------------------
	["118.89.30.179"]   = "map0_gate_m0",
	["193.112.186.133"] = "map0_r1_gate_m",
	["119.29.189.208"]  = "map0_r2",

	["119.29.193.196"]  = "map0_profile_r2",

	["106.52.93.78"]    = "rent_server0",

	["123.207.235.22"]  = "post_22_gate_s0",
	["203.195.177.104"] = "gate_s",
	["193.112.23.173"]  = "gate_s",

	["159.75.41.227"]   = "gate_s",
	["159.75.37.13"]    = "gate_s",

	["159.75.41.251"]   = "gate_m_map_r3",
	["159.75.41.135"]   = "gate_m",
	["42.193.186.192"]  = "gate_m",


	["118.89.65.140"]   = "log_140",

	-------------ssdb + dc ----------------
	["111.230.134.243"] = "map0_ssdb0_profile_r1",
	["182.254.181.138"] = "map0_ssdb1",
	["111.230.7.240"]   = "map0_ssdb2",
	["123.207.123.91"]  = "map0_ssdb3_gate_m",
	["139.199.1.78"]    = "map0_ssdb4_profile0_gate_m0",
	["134.175.84.221"]  = "map0_ssdb5_profile0_r1",
	["129.204.85.213"]  = "map0_ssdb6_gate_m",
	["139.199.76.205"]  = "map0_ssdb7",
	["111.230.236.192"] = "map0_ssdb8",
	["203.195.175.68"]  = "map0_ssdb9",


	--------------海外--------------------------
	["47.88.2.143"]   = "hw_ma_map",
	["47.254.69.196"] = "hw_profile",
	--]]

}


function FOO.getDescByIP( ip_ )
	-- 优先配置
	if  FOO.ip_desc[ip_] then
		return FOO.ip_desc[ip_]
	end

	-- 共享内存上报的name
	local name_ = uu.get_server_cache_table( 1, 'ipn_' .. ip_ )
	if  type(name_) == 'table' and name_.v then
		return name_.v
	end

	return ""
end



FOO.header = [[<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>keeper_list</title>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/angular.min.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/cookie.min.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/md5.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/jquery-3.1.1.min.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/miniajax.js"></script>
</head>
<body>]];


FOO.tail = [[
</body>
</html>
]];


FOO.show = function( data_, ctrl_ )
	ngx.say( FOO.header )

	FOO.now = uu.now()
	ngx.say (  '<script type="text/javascript"> var g_now=' .. FOO.now .. '; </script>\n' );

	local t_group_ = {
		keys = {
			"id",
			"env",
			"ip",
			"bs",
			"desc",
			--"hostname",
			"ver",
			"time",
			"nginx_list",
		},
		style = {
			--'width="128px"',
			--'width="150px"',
			--'',
			--'width="128px"',
		},
	}

	if  ctrl_ == "159" then
		t_group_.keys[ #t_group_.keys + 1 ] = "ctrl"
	end


	local server_name_         ----服务器名字过滤 _ma_gate_  _dc_
	local find_server_name_    ----有server_name的情况下，是否已经找到
	if  type(ngx.ctx.m_params.server_name) == 'string' and #ngx.ctx.m_params.server_name>0 then
		server_name_ = ngx.ctx.m_params.server_name
	end

	for ip_, keeper_info_list_ in pairs( data_ ) do
		if  type( keeper_info_list_ ) == 'table' then

			local tmp_group_ = {
				id   = 0,
				ip   = ip_,
				desc = FOO.getDescByIP( ip_ ),
				--hostname = keeper_info_list_.hostname,
				env  = keeper_info_list_.env,
				ver  = keeper_info_list_.keeper_ver,
				time = keeper_info_list_.t,
				nginx_list = '',
			}

			if  not (tmp_group_.desc and #tmp_group_.desc>0) then
				tmp_group_.desc = keeper_info_list_.hostname
			end

			if  ctrl_ == '159' then
				tmp_group_.bs = FOO.create_checkbox_button( ip_ )   --cb_server_ip_list
			end

			find_server_name_ = 0
			if  keeper_info_list_.nginx_list  then
				for _, or_info_ in pairs(keeper_info_list_.nginx_list ) do
					--tmp_group_.or_list
					if  type(or_info_) == 'table' and or_info_.name then
						if  or_info_.name == 'openresty_keeper_x.conf' then
							-- 不显示keeper
						elseif  server_name_ then
							-- 有过滤条件的情况下
							if  string.find( or_info_.name, server_name_ ) then
								find_server_name_ = 1
								tmp_group_.nginx_list = tmp_group_.nginx_list .. or_info_.name .. '<br>'
							end
						else
							tmp_group_.nginx_list = tmp_group_.nginx_list .. or_info_.name .. '<br>'
						end

					end
				end
			end

			-- 有过滤条件的情况下，判断版本
			if  server_name_ and tmp_group_.ver and tmp_group_.env and tmp_group_.ip then
				local ver_string_ = FOO.check_ver_lua_hot( server_name_, tmp_group_ )
				if  ver_string_ and #ver_string_ > 0 then
					tmp_group_.ver = tmp_group_.ver .. ver_string_
				end
			end

			if  tmp_group_.time > 900 then    ---15分钟
				tmp_group_.time = '<font color="red">(已掉线)' .. tmp_group_.time .. "</font>"
			end


			if  ctrl_ == '159' then
				local time_ = uu.now()
				local tt_ = {
					uin = 1166200,
					time = time_,
					cmd = 'getKeeperDetail',
					--token = ns_auth_comm_checker.gen_comm_inner_token( 1166200, time_, "getKeeperDetail" )
					ctoken = data_.ctoken
				}

				local url_ = 'https://indevelop.mini1.cn:8876/miniw/center?' .. ngx.encode_args( tt_ ) .. "&ip=" .. ip_
				local sub_ = 'ip_' .. ip_
				tmp_group_.ctrl = FOO.create_open_new_window_button( url_, sub_ , "管理", "open_detail" )
			end


			if  server_name_ then
				---有server_name过滤
				if  find_server_name_ == 1 then
					t_group_[ #t_group_ + 1 ] = tmp_group_
				end
			else
				t_group_[ #t_group_ + 1 ] = tmp_group_
			end

		end
	end


	---需要进行排序
	local  sort_ = function( a, b )
		if  type( a ) == 'table' and type( b ) == 'table' then

			if  a.env and b.env and (a.env ~= b.env) then
				return a.env < b.env
			end

			if  a.desc and b.desc and #a.desc>0 and #a.desc>0 and ( a.desc ~= b.desc ) then
				return a.desc < b.desc
			end

			if  a.hostname and b.hostname and #a.hostname>0 and #a.hostname>0 and ( a.hostname ~= b.hostname ) then
				return a.hostname < b.hostname
			end

			if  a.ip and b.ip and #a.ip>0 and #a.ip>0 and ( a.ip ~= b.ip ) then
				return a.ip < b.ip
			end
		end
		return false
	end

	table.sort( t_group_, sort_ )

	for i=1, #t_group_ do
		t_group_[i].id = i;
	end

	local ht_node_ = CHtmlTable:new( t_group_ )
	local keeper_list_string_ = ht_node_:get_print_string()


	ngx.say( '<table border=3 cellpadding=10>' )
	ngx.say( '<tr><td valign="top">' )
		ngx.say( "<H2> openresty(OR)节点列表管理 server_name=XXX(可过滤) </H2>" )
		ngx.say( '<table border=3 cellpadding=10>' )
		ngx.say( '<tr><td>' )
		ngx.say( keeper_list_string_ )
		ngx.say( '</td></tr>' )
		ngx.say( '</table>' )
		ngx.say( FOO.ret_string )
	ngx.say( '</td><td valign="top">' )
		ngx.say( FOO.iframe_right )
	ngx.say( '</td></tr>' )
	ngx.say( '</table>' )

	ngx.say( '<br><hr>' )
	ngx.say( FOO.js_func )    	---增加js函数
	ngx.say( FOO.tail )

end


-- 如果有dc ma_gate dc_gate 判断lua_ver lua_hot版本显示，由cmds.reportLoad接口上报
--local key_ =  pp_.load_name .. "_" .. tmp_group_.env .. "_" .. tmp_group_.ip
function FOO.check_ver_lua_hot( server_name_, tmp_group_ )

	log.debug( "call check_ver_lua_hot --> " .. server_name_ )
	uu.var_dump( tmp_group_ )

	local ver_string_ = ''
	if  server_name_ == 'gate' or server_name_ == 'ma_gate' or server_name_ == 'dc' then

		local function add_ver_string_ ( s_name_, shared_ )
			local key_ =  s_name_ .. "_" .. tmp_group_.env .. "_" .. tmp_group_.ip
			local rp_string_ = shared_:get( key_ )
			if  rp_string_ then
				log.debug( "get rp_string=" .. rp_string_ )
				local rp_ = table.loadstring( rp_string_ )
				if  type(rp_) == 'table' then
					if  rp_.ver_lua then
						ver_string_ = ver_string_ .. '<br>' .. rp_.ver_lua
					end
					if  rp_.ver_hot then
						ver_string_ = ver_string_ .. '<br>' .. rp_.ver_hot
					end
				end
			end
		end

		add_ver_string_( 'ma_gate',    ngx.shared.ma_gate_list )
		add_ver_string_( 'dc_gate',    ngx.shared.dc_gate_list )
		add_ver_string_( 'data_cache', ngx.shared.data_cache_list )
	end

	return ver_string_
end



----------------------------------------------------------

---按照更新的模块，生成按钮
function FOO.create_modules_button( modules_ )
	local str_ = ""
	for i=1, #modules_ do
		str_ = 	str_ .. FOO.create_button_str( "keeper_action", 13011401, "update", modules_[i], "read", "1", "1" )
	end
	return str_
end


---传入一个链接，打开新窗口
function FOO.create_open_new_window_button( url_, sub_, button_name_, function_name_ )
	return '<button style="background-color:#00ffff" onclick="' ..
			function_name_ .. '(this, \'' .. url_ .. '\', \'' .. sub_ .. '\')" >' .. button_name_ .. '</button>'
end

function FOO.create_checkbox_button( value_ )
	return '<input style="zoom:125%;" type="checkbox" name="cb_server_ip_list" class="cb"'
			.. ' onclick=" press_checkbox(this); " value="' .. value_ .. '" />'
end



FOO.create_ctrl_buttons = function( ip_, button_name_, op_, params_ )
	local auth_ = ns_auth_comm_checker.gen_comm_inner_token( 13011401, FOO.now, "keeper_action" )
	local ret_ =   FOO.create_button_str( "keeper_action", 13011401, op_, button_name_, auth_, ip_, params_ )
	return ret_
end


FOO.create_input_str = function( id_, value_, width_ )
	return '<input type=text id="' .. id_ .. '" style="width:' .. (width_ or 30)
			.. 'px; height:20px; border:solid 1px; text-align:center;" value="' .. (value_ or "") .. '" />'
end


FOO.create_button_str = function( function_name_, uin_, op_, button_name_, auth_, ip_, params_ )
	return '<button style="background-color:#00ffff" onclick="' ..
			function_name_ .. '(' .. uin_ .. ',\'' .. ip_ .. '\',\'' ..  op_
			.. '\',\'' .. auth_ .. '\',\'' .. params_ .. '\')" >' .. button_name_ .. '</button>'
end


FOO.create_img_str = function( value_, width_ )
	return '<image width=' .. (width_ or 30) .. ' src="' .. (value_ or "") .. '" ></image>'
end


FOO.iframe_right = [[
<iframe id="_iframe_ret" width="840px" height="2500px" float:right; src="" ></iframe>
]];

FOO.ret_string = [[
<table>
<textarea id="_ret_string" style="width:800px;height:400px;background-color:#dddddd;" readonly="readonly">
 ... </textarea>
</table>
]];

FOO.js_func = [[
<script type="text/javascript">

    function press_checkbox(this_){
        if (this_.checked){
            this_.style="zoom:175%;";
        }else{
            this_.style="zoom:125%;";
        }
        document.getElementById("_iframe_ret" ).src = "";
    }

	function open_detail( button_obj, url_, sub_ ){
		button_obj.style.backgroundColor = "#00ff00";
		//window.open( url_, sub_ );
		//判断是否是多选
		var ip_lists = document.getElementsByName('cb_server_ip_list');
		var value_str = "";
		for(var i = 0; i < ip_lists.length; i++){
			if(ip_lists[i].checked){
				value_str = value_str + ip_lists[i].value + ','
			}
		}
		if ( value_str.length > 0 ){
			url_ = url_ + '&server_ip_list=' + value_str;
		}
		document.getElementById("_iframe_ret" ).src = url_;
		//document.getElementById("_ret_string").innerHTML = url_;
	};


	function keeper_action( uin_, node_group_, node_id_, op_, auth_, num_ ){
		var press_yes = confirm( op_ + " " + node_group_ + "_" + node_id_ + "\n\n是否确定？" );
		if (press_yes) {
			//get请求

			document.getElementById("_ret_string").innerHTML = " waiting ... ";

			var url_ = "";
			if ( op_.length > 8 ) {
				url_ = "/miniw/rent_server?cmd=keeper_action&time="+g_now+"&op="+op_+"&num="+num_
				        +"&uin="+uin_+"&node_group="+node_group_+"&node_id="+node_id_+"&token="+auth_;
			}
			else{
				alert( "unknown op" );
				return;
			}

			var post_data_ = {};
			ajax({
				url: url_,
				type: "POST",
				data: post_data_,
				dataType: "json",
				success: function (response, xml) {
					document.getElementById("_ret_string").innerHTML = response;
					//alert( response );
					//location.reload();
				},
				fail: function (status) {
					alert( "服务器通讯失败，请联系海马 ......" );
				}
			});
		}
	}

</script>
]];


-----------------------------------------------------------
---清理输出
FOO.clean_txt = function()
	FOO.show_txt = {};
end

---增加输出内容
FOO.add_txt = function( txt_ )
	FOO.show_txt[ #FOO.show_txt + 1 ] = txt_
end


---获得所有输出
FOO.get_txt = function()
	return table_concat( FOO.show_txt )
end


return FOO;